import {messages} from "share/common";
import React from 'react'
import { connect } from 'react-redux'
import menuRoute from 'routes/menuRoute'
import moment from 'moment'
import { Form, Tabs, message, Spin, Button, Icon } from 'antd'
const TabPane =Tabs.TabPane;

import beepTimerService from 'containers/setting/beep-timer/beep-timer.service'
import BeepForm from 'containers/setting/beep-timer/beep-form'
import BeepInfo from 'containers/setting/beep-timer/beep-info'
import Condition from 'components/condition'
const { If, Else } = Condition;

import 'styles/setting/beep-timer/beep-timer.scss'

class BeepTimer extends React.Component{
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      pageLoading: false,
      tabs: [
        {key: 'REGULARLY_REMIND', name:messages('setting.key120'/*定时提醒*/)},
        {key: 'TRAVEL', name:messages('setting.key1443'/*差旅申请*/)},
        {key: 'BUSINESS_CARD_REMIND', name: messages('setting.key123'/*商务卡提醒*/)},
        {key: 'EXPENSE_REPORT', name: messages('setting.key124'/*报销提醒*/)},
        {key: 'REPAYMENT', name: messages('setting.key1879')/*还款提醒*/},
        {key: 'EXPENSE_INVOICE', name: messages('setting.key1981')/*交票提醒*/}
      ],
      status: 'REGULARLY_REMIND',
      rowsData: [],
      businessCard: [],
      isNew: false,
      isEdit: false,
      supplierManagement: menuRoute.getRouteItem('overview','key'), //供应商管理列表
    };
  }

  componentDidMount(){
    this.getList();
    this.getBusinessCard()
  }

  getList = () => {
    this.setState({ pageLoading: true });
    let params = {companyOID: this.props.company.companyOID};
    beepTimerService.getFormsByOIDs(params).then(res => {
      this.setState({
        pageLoading: false,
        rowsData: res.data.rows,
        isEdit: false,
        isNew: false
      })
    }).catch(() => {
      this.setState({ pageLoading: false });
      message.error(messages('setting.key125'/*数据获取失败*/))
    })
  };

  onChangeTabs = (key) => {
    this.handNewCancel();
    this.handUpdateCancel();
    this.setState({ status: key })
  };

  //获取商务卡列表
  getBusinessCard = () => {
    beepTimerService.getBusinessCardType().then(res => {
      this.setState({ businessCard: res.data.rows })
    })
  };

  //新建
  handleNew = () => {
    if(this.state.isEdit) {
      message.warning(messages('setting.key126'/*你有一个编辑中的内容*/));
      return
    }
    this.setState({ isNew: true })
  };

  //编辑
  handleEdit = (values) =>{
    if(this.state.isEdit || this.state.isNew) {
      message.warning(messages('setting.key126'/*你有一个编辑中的内容*/));
      return
    }
    let rowsData = this.state.rowsData;
    rowsData.map(item => {
      if (item.id === values.id) {
        item.isEdit = true;
        item.conditionId = values.conditionId;
      }
    });
    this.setState({ rowsData, isEdit: true })
  };

  //保存
  handleSubmit = (values) => {
    const { company } = this.props;
    this.setState({ loading: true });
    let params = {
      companyOID: company.companyOID,
      tenantID: company.tenantId,
      enabledFlag: true,
      hour: Number(String(values.hour).split(':')[0])
    };

    if (this.state.status === 'REGULARLY_REMIND') {
      params.code = 'InvoiceScheduledNoticeTask';
      params.month = Number(moment(values.sendDate).format('MM'));
      params.date = Number(moment(values.sendDate).format('DD'));
      params.params = JSON.stringify({
        title: values.title,
        content: values.content
      })
    }
    if (this.state.status === 'TRAVEL') {
      params.code = 'TravelApplicationNoticeTask';
      params.params = JSON.stringify({
        title: values.title,
        content: values.content,
        remindDay: values.remindDay,
        formOIDs: values.formOIDs
      })
    }
    if (this.state.status === 'BUSINESS_CARD_REMIND') {
      params.code = 'BankCardTask';
      params.date = values.date;
      params.params = JSON.stringify({
        title: values.title,
        content: values.content,
        consumeTypes: values.consumeTypes,
        bankCardTypes: values.bankCardTypes,
        remindTypes: values.remindTypes,
        billingPeriodTypes: values.billingPeriodTypes
      })
    }
    if (this.state.status === 'EXPENSE_REPORT') {
      params.code = 'ExpenseReportNoticeTask';
      let rejectType = [];
      if (values.expenseStatus) {
        values.expenseStatus.map((item, index) => {
          item.length > 4 ? rejectType.push(item.substr(4)) : rejectType.push('1000');
          values.expenseStatus[index] = item.substr(0, 4);
        });
      }
      params.params = JSON.stringify({
        title: values.title,
        content: values.content,
        remindDay: values.remindDay,
        target: values.target,
        labels: values.labels,
        invoiceStatus: values.invoiceStatus,
        remindTypes: values.remindTypes,
        status: values.expenseStatus || [],
        rejectType: rejectType
      })
    }
    if (this.state.status === 'REPAYMENT') {
      params.code = 'RepaymentNoticeTask';
      params.params = {
        title: values.title,
        content: values.content,
        repaymentRemindPersonTypes: values.repaymentRemindPersonTypes,
        repaymentRemindTypes: values.repaymentRemindTypes,
        repaymentRemindBaseDateType: values.repaymentRemindBaseDateType,
        differenceDate: values.differenceDate
      };
      values.fitObj === 'formOids' && (params.params.formOids = values.formOids);
      values.fitObj === 'loanTypeIds' && (params.params.loanTypeIds = values.loanTypeIds);
      params.params = JSON.stringify(params.params);
    }
    if (this.state.status === 'EXPENSE_INVOICE') {
      params.code = 'ExpenseReportPasteReceiptNoticeTask';
      params.params = JSON.stringify({
        title: values.title,
        content: values.content,
        remindDay: values.remindDay,
        target: values.target,
        remindTypes: values.remindTypes,
        formOids: values.formOids || []
      })
    }
    values.id && (params.id = values.id);
    let method = values.id ? 'updateBeepTimer' : 'newBeepTimer';
    beepTimerService[method](params).then(res => {
      if (['REPAYMENT', 'EXPENSE_REPORT', 'EXPENSE_INVOICE'].indexOf(this.state.status) !== -1) {
        beepTimerService.saveHonestInfo({
          companyOID: company.companyOID,
          taskId: values.id || res.data.rows.id ,
          conditionId: values.conditionId
        }).then(() => {
          message.success(messages('common.save.success', {name: ""})/*保存成功*/);
          this.handUpdateCancel(values);
          this.handNewCancel();
          this.getList();
          this.setState({ loading: false })
        })
      } else {
        message.success(messages('common.save.success', {name: ""})/*保存成功*/);
        this.handUpdateCancel(values);
        this.handNewCancel();
        this.getList();
        this.setState({ loading: false })
      }
    }).catch(e => {
      this.setState({ loading: false });
      message.error(`${messages('common.save.filed')}，${e.response.data.message}`/*保存失败*/)
    })
  };

  //删除
  handleDelete = (value) =>{
    beepTimerService.deleteTraveApprove([value.id]).then(() => {
      message.success(messages('common.delete.success', {name: ""})/*{name} 删除成功*/);
      this.getList()
    }).catch(e => {
      message.error(`${messages('setting.key127'/*删除失败*/)}，${e.response.data.message}`)
    })
  };

  //取消新建
  handNewCancel = () => {
    this.setState({ isNew: false })
  };

  //取消编辑
  handUpdateCancel = () => {
    let rowsData = this.state.rowsData;
    rowsData.map(item => { item.isEdit = false });
    this.setState({ rowsData, isEdit: false })
  };

  //跳转供应商管理
  toSupplierManagement = () => {
    // this.context.router.push(this.state.supplierManagement.url)
    window.open(this.state.supplierManagement.url)
  };

  renderContent = () => {
    const { loading, rowsData, isNew, businessCard } = this.state;
    let content = null;
    switch (this.state.status){
      case 'REGULARLY_REMIND':
        content = (
          <div className="regularly-remind">
            <div className="header">{messages('setting.key128'/*可在指定日期提醒员工指定内容*/)}</div>
            {rowsData.map(item => {
              if(item.code === "InvoiceScheduledNoticeTask") {
                return item.isEdit ? (
                  <BeepForm key={item.id}
                            type="regularly"
                            editData ={item}
                            loading={loading}
                            submitHandle ={this.handleSubmit}
                            handCancel={this.handUpdateCancel}/>
                ) : (
                  <BeepInfo type="regularly"
                            applyData={item}
                            key={item.id}
                            onEdit={this.handleEdit}
                            onDelete={this.handleDelete}/>
                )
              }
            })}
            {isNew ? (
              <BeepForm type="regularly"
                        loading={loading}
                        submitHandle ={this.handleSubmit}
                        handCancel={this.handNewCancel}/>
            ) : (
              <Button type="dashed" className="btn-add" onClick={this.handleNew}><Icon type="plus" />{messages('common.add')}{/*添加*/}</Button>
            )}
          </div>
        );
        break;
      case 'TRAVEL':
        content = (
          <div className="apply-traver">
            <div className="header">1、{messages('setting.key129'/*只在申请单未关闭且未关联报销单时提醒*/)}</div>
            <div className="header">2、{messages('setting.key130'/*每个单据可以设置多条提醒规则，每条规则都会发送提醒，即支持多次提醒*/)}</div>
            {rowsData.map(item => {
              if(item.code === "TravelApplicationNoticeTask") {
                return item.isEdit ? (
                  <BeepForm key={item.id}
                            type="traver"
                            editData ={item}
                            loading={loading}
                            titlePlaceholder={messages('setting.key131'/*出差结束提醒*/)}/*"出差结束提醒"*/
                            contentPlaceholder={messages('setting.key132'/*请及时报销*/)}
                            submitHandle ={this.handleSubmit}
                            handCancel={this.handUpdateCancel}/>
                ) : (
                  <BeepInfo type="traver"
                            applyData={item}
                            key={item.id}
                            onEdit={this.handleEdit}
                            onDelete={this.handleDelete}/>
                )
              }
            })}
            {isNew ? (
              <BeepForm type="traver"
                        loading={loading}
                        titlePlaceholder={messages('setting.key131'/*出差结束提醒*/)}
                        contentPlaceholder={messages('setting.key132'/*请及时报销*/)}
                        submitHandle ={this.handleSubmit}
                        handCancel={this.handNewCancel}/>
            ) : (
              <Button type="dashed" className="btn-add" onClick={this.handleNew}>
                <Icon type="plus" /> {messages('common.add')}{/*添加*/}
              </Button>
            )}
          </div>
        );
        break;
      case 'BUSINESS_CARD_REMIND':
        content = (
          <div className="business-card-remind">
            {businessCard.length > 0 ? (
              <div>
                <div className="header">{messages('setting.key136'/*1、对于指定账单月，且未生成费用或未提交报销单的商务卡消费数据，发送提醒*/)}</div>
                <div className="header">{messages('setting.key137'/*2、可以设置多条提醒规则，每条规则都会发送提醒，即支持多次提醒*/)}</div>
                {rowsData.map(item => {
                  if(item.code === "BankCardTask") {
                    return item.isEdit ? (
                      <BeepForm key={item.id}
                                type="business-card"
                                editData ={item}
                                loading={loading}
                                titlePlaceholder={messages('setting.key138'/*商务卡消费报销提醒*/)}
                                contentPlaceholder={messages('setting.key132'/*请及时报销*/)}
                                submitHandle ={this.handleSubmit}
                                handCancel={this.handUpdateCancel}/>
                    ) : (
                      <BeepInfo type="business-card"
                                applyData={item}
                                key={item.id}
                                onEdit={this.handleEdit}
                                onDelete={this.handleDelete}/>
                    )
                  }
                })}
                {isNew ? (
                  <BeepForm type="business-card"
                            loading={loading}
                            titlePlaceholder={messages('setting.key138'/*商务卡消费报销提醒*/)}
                            contentPlaceholder={messages('setting.key132'/*请及时报销*/)}
                            submitHandle ={this.handleSubmit}
                            handCancel={this.handNewCancel}/>
                ) : (
                  <Button type="dashed" className="btn-add" onClick={this.handleNew}>
                    <Icon type="plus" /> {messages('common.add')}{/*添加*/}
                  </Button>
                )}
              </div>
            ) : (
              <div className="business-card-remind-center">
                <div className="business-card-remind-title">
                  <Icon type="copy" />{messages('setting.key139'/*您尚未开通服务*/)}
                </div>
                <div>
                  {messages('setting.key140'/*请先启用商务卡*/)}，<a onClick={this.toSupplierManagement}>{messages('setting.key141'/*前往开通服务*/)}</a>
                </div>
              </div>
            )}
          </div>
        );
        break;
      case 'EXPENSE_REPORT':
        content = (
          <div>
            <div className="header">1、{messages('setting.key142'/*只对规则范围内的费用进行报销提醒*/)}</div>
            <div className="header">2、{messages('setting.key143'/*每笔费用可以设置多条提醒规则，每条规则都会发送提醒，即支持多次提醒*/)}</div>
            <div className="header">3、{messages('setting.key144'/*若未在系统中维护提醒对象数据，此条提醒将不会发送*/)}</div>
            {
              rowsData.map(item => {
                if(item.code === 'ExpenseReportNoticeTask'){
                  return item.isEdit ? (
                    <BeepForm key={item.id}
                              type="expense-report"
                              editData ={item}
                              loading={loading}
                              titlePlaceholder={messages('setting.key145'/*费用报销提醒*/)}
                              contentPlaceholder={messages('setting.key78'/*需尽快报销*/)}
                              submitHandle ={this.handleSubmit}
                              handCancel={this.handUpdateCancel}/>
                  ) : (
                    <BeepInfo type="expense-report"
                              applyData={item}
                              key={item.id}
                              onEdit={this.handleEdit}
                              onDelete={this.handleDelete}/>
                  )
                }
              })
            }
            {
              isNew ? (
                <BeepForm type="expense-report"
                          loading={loading}
                          titlePlaceholder={messages('setting.key145'/*费用报销提醒*/)}
                          contentPlaceholder={messages('setting.key78'/*需尽快报销*/)}
                          submitHandle ={this.handleSubmit}
                          handCancel={this.handNewCancel}/>
              ) : (
                <Button type="dashed" className="btn-add" onClick={this.handleNew}><Icon type="plus" /> {messages('common.add')}{/*添加*/}</Button>
              )
            }
          </div>
        );
        break;
      case 'REPAYMENT':
        content = (
          <div>
            <div className="header">1、{messages('setting.key133')/*只对未完成还款的借款申请单提醒*/}</div>
            <div className="header">2、{messages('setting.key130')/*每个单据可以设置多条提醒规则，每条规则都会发送提醒，即支持多次提醒*/}</div>
            {
              rowsData.map(item => {
                if(item.code === 'RepaymentNoticeTask'){
                  return item.isEdit ? (
                    <BeepForm key={item.id}
                              type="repayment"
                              editData ={item}
                              loading={loading}
                              titlePlaceholder={messages('setting.key134')/*借款还款提醒*/}
                              contentPlaceholder={messages('setting.key135')/*请及时还款*/}
                              submitHandle ={this.handleSubmit}
                              handCancel={this.handUpdateCancel}/>
                  ) : (
                    <BeepInfo type="repayment"
                              applyData={item}
                              key={item.id}
                              onEdit={this.handleEdit}
                              onDelete={this.handleDelete}/>
                  )
                }
              })
            }
            {
              isNew ? (
                <BeepForm type="repayment"
                          loading={loading}
                          titlePlaceholder={messages('setting.key134')/*借款还款提醒*/}
                          contentPlaceholder={messages('setting.key135')/*请及时还款*/}
                          submitHandle ={this.handleSubmit}
                          handCancel={this.handNewCancel}/>
              ) : (
                <Button type="dashed" className="btn-add" onClick={this.handleNew}><Icon type="plus" /> {messages('common.add')}{/*添加*/}</Button>
              )
            }
          </div>
        );
        break;
      case 'EXPENSE_INVOICE':
        content = (
          <div>
            <div className="header">1、{messages('setting.key1982')/*只对规则范围内，没有交过单（或没有审核通过）且不含“免打印”标签的报销单进行交票提醒*/}</div>
            <div className="header">2、{messages('setting.key1983')/*每张报销单可以设置多条提醒规则，每条规则都会发送提醒，即支持多次提醒*/}</div>
            <div className="header">3、{messages('setting.key144'/*若未在系统中维护提醒对象数据，此条提醒将不会发送*/)}</div>
            {rowsData.map(item => {
              if (item.code === 'ExpenseReportPasteReceiptNoticeTask') {
                return (
                  <Condition>
                    <If value={item.isEdit}>
                      <BeepForm key={item.id}
                                type="expense-invoice"
                                editData ={item}
                                loading={loading}
                                titlePlaceholder={messages('setting.key145'/*费用报销提醒*/)}
                                contentPlaceholder={messages('setting.key78'/*需尽快报销*/)}
                                submitHandle={this.handleSubmit}
                                handCancel={this.handUpdateCancel}/>
                    </If>
                    <Else>
                      <BeepInfo type="expense-invoice"
                                applyData={item}
                                key={item.id}
                                onEdit={this.handleEdit}
                                onDelete={this.handleDelete}/>
                    </Else>
                  </Condition>
                )
              }
            })}
            <Condition>
              <If value={isNew}>
                <BeepForm type="expense-invoice"
                          loading={loading}
                          titlePlaceholder={messages('setting.key1984')/*报销单交票提醒*/}
                          contentPlaceholder={messages('setting.key1976')/*需尽快交票*/}
                          submitHandle ={this.handleSubmit}
                          handCancel={this.handNewCancel}/>
              </If>
              <Else>
                <Button type="dashed" className="btn-add" onClick={this.handleNew}>
                  <Icon type="plus" /> {messages('common.add')/*添加*/}
                </Button>
              </Else>
            </Condition>
          </div>
        );
        break;
    }
    return content;
  };

  render(){
    const { pageLoading, tabs, status } = this.state;
    return (
      <div className="beep-timer">
        <Tabs type="line" tabPosition="left" activeKey={status} onChange={this.onChangeTabs}>
          {tabs.map(item => {
            return (
              <TabPane tab={item.name} key={item.key}>
                {item.key === status && <Spin spinning={pageLoading}>{this.renderContent()}</Spin>}
              </TabPane>
            )
          })}
        </Tabs>
      </div>
    )
  }
}

BeepTimer.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps(state) {
  return {
    company: state.login.company,
  }
}

const wrappedBeepTimer = Form.create()(BeepTimer);

export default connect(mapStateToProps)(wrappedBeepTimer);
